<!--字典类型-->
<script setup lang="ts">
interface User {
  name: string;
  code: string;
  status: boolean;
}
const tableRowClassName = ({ row, rowIndex }: { row: User; rowIndex: number }) => {
  if (!row.status) {
    return "warning-row";
  } else {
    return "";
  }
};
import {
  getDictTypePage,
  getDictTypeForm,
  addDictType,
  updateDictType,
  deleteDictTypes,
} from "@/api/dict";
import {
  Document, DocumentCopy, Check, Close
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'
import { DictTypePageVO, DictTypeQuery, DictTypeForm } from "@/api/dict/types";
import { Codemirror } from "vue-codemirror";

defineOptions({
  name: "merchantList",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);
const messageDialog = ref(false)

const queryParams = reactive<DictTypeQuery>({
  pageNum: 1,
  pageSize: 10,
});

//const dictTypeList = ref<DictTypePageVO[]>();

const dialog = reactive({
  title: "",
  visible: false,
});

/* 复制代码 */
const toggleIconAndCopy = (scope) => {  
  scope.row.showCheckIcon = !scope.row.showCheckIcon;  
  if (scope.row.showCheckIcon) {  
    // 当图标切换为"check icon"时，触发复制功能  
    const textArea = document.createElement('textarea');
    textArea.value = scope.row.code;
    document.body.appendChild(textArea);
    textArea.select();

    try {
      const successful = document.execCommand('copy');
      if (successful) {
        ElMessage({  
          message: '复制成功',  
          type: 'success',  
        });  
        console.log('复制成功');
      } else {
        throw new Error('复制失败');
      }
    } catch (err) {
      ElMessage.error('复制失败');
      console.error('复制失败', err);
    } finally {
      document.body.removeChild(textArea);
    }
  }  
};

const onCopyClick = () => {
    const textArea = document.createElement('textarea');
    textArea.value = jsonData.value;
    document.body.appendChild(textArea);
    textArea.select();

    try {
        const successful = document.execCommand('copy');
        if (successful) {
            ElMessage({
                message: '复制成功',
                type: 'success',
            });
            console.log('复制成功');
            //showCheckIcon.value = true;
        } else {
            throw new Error('复制失败');
        }
    } catch (err) {
        ElMessage.error('复制失败');
        console.error('复制失败', err);
    } finally {
        document.body.removeChild(textArea);
    }
};

const onCopyClick2 = () => {
    const textArea = document.createElement('textarea');
    textArea.value = jsonData2.value;
    document.body.appendChild(textArea);
    textArea.select();

    try {
        const successful = document.execCommand('copy');
        if (successful) {
            ElMessage({
                message: '复制成功',
                type: 'success',
            });
            console.log('复制成功');
            //showCheckIcon.value = true;
        } else {
            throw new Error('复制失败');
        }
    } catch (err) {
        ElMessage.error('复制失败');
        console.error('复制失败', err);
    } finally {
        document.body.removeChild(textArea);
    }
};
const onCopyClick3 = () => {
    const textArea = document.createElement('textarea');
    //textArea.value = jsonData.value;
    document.body.appendChild(textArea);
    textArea.select();

    try {
        const successful = document.execCommand('copy');
        if (successful) {
            ElMessage({
                message: '复制成功',
                type: 'success',
            });
            console.log('复制成功');
            //showCheckIcon.value = true;
        } else {
            throw new Error('复制失败');
        }
    } catch (err) {
        ElMessage.error('复制失败');
        console.error('复制失败', err);
    } finally {
        document.body.removeChild(textArea);
    }
};

const formData = reactive<DictTypeForm>({
  status: 1,
});
/* 下拉多选 */
const handleItemClick = (operator: string): void => {
  // 处理下拉菜单项的点击事件，可以在这里执行相关逻辑
  console.log('Selected operator:', operator);
};
const rules = reactive({
  name: [{ required: true, message: "请输入字典类型名称", trigger: "blur" }],
  code: [{ required: true, message: "请输入字典类型编码", trigger: "blur" }],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  getDictTypePage(queryParams)
    .then(({ data }) => {
      dictTypeList.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中  */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/**
 * 打开字典类型表单弹窗
 *
 * @param dicTypeId 字典类型ID
 */
function openDialog(dicTypeId?: number) {
  dialog.visible = true;
  if (dicTypeId) {
    dialog.title = "修改字典类型";
    getDictTypeForm(dicTypeId).then(({ data }) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增字典类型";
  }
}

/* 退款谈话框 */
function openDictDialog2(row: DictTypePageVO) {
  dictDataDialog.visible = true;
  dictDataDialog.title = "【" + row.name + "】字典数据";

  selectedDictType.typeCode = row.code;
  selectedDictType.typeName = row.name;
}
/**  关闭字典数据弹窗 */
function closeDictDialog2() {
  dictDataDialog.visible = false;
}

/** 字典类型表单提交 */
function handleSubmit() {
  dataFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      loading.value = false;
      const dictTypeId = formData.id;
      if (dictTypeId) {
        updateDictType(dictTypeId, formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        addDictType(formData)
          .then(() => {
            ElMessage.success("新增成功");
            closeDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}


/* 详情 */
const code = ref('');
const lines = ref([]);
const currentLines = ref([]); // 用于显示当前行数的数组  
const updateLineNumbers = () => {
  lines.value = code.value.split('\n');
  currentLines.value = lines.value.slice(0, 10); // 假设最多显示10行，可以根据需要调整  
};
/* 详情文本 */
const jsonData = {
  "consoleSecret": "DsM3vn9HKjnnAH3xRXRZ",
  "originNotifyIp": "154.23.187.163",
  "amount": 10,
  "mockOrderNo": "mock_6ed26d9c47694fb7a775dc4cdd1205f6",
  "requestOrderNo": "T121302283235Af7kULCv",
  "status": "SUCCESS"
}
const jsonString = ref(JSON.stringify(jsonData, null, 2));

const jsonData2 = {
  "host": "api.tianshupay.com",
  "connection": "close",
  "x-forwarded-for": "154.23.187.163, 154.23.187.163, 154.23.187.163",
  "content-length": "200",
  "content-type": "application/json; charset=utf-8",
  "x-real-ip": "154.23.187.163",
  "accept-encoding": "gzip",
  "user-agent": "okhttp/3.14.9"
}
const jsonString2 = ref(JSON.stringify(jsonData2, null, 2));

/** 关闭字典类型弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/**  重置字典类型表单 */
function resetForm() {
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();

  formData.id = undefined;
  formData.status = 1;
}

/** 删除字典类型 */
function handleDelete(dictTypeId?: number) {
  const dictTypeIds = [dictTypeId || ids.value].join(",");
  if (!dictTypeIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteDictTypes(dictTypeIds).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

const dictDataDialog = reactive({
  title: "",
  visible: false,
});

const selectedDictType = reactive({ typeCode: "", typeName: "" }); // 当前选中的字典类型

/** 打开字典数据弹窗 */
function openDictDialog(row: DictTypePageVO) {
  dictDataDialog.visible = true;
  dictDataDialog.title = "【" + row.name + "】字典数据";

  selectedDictType.typeCode = row.code;
  selectedDictType.typeName = row.name;
}

/**  关闭字典数据弹窗 */
function closeDictDialog() {
  dictDataDialog.visible = false;
}

onMounted(() => {
  handleQuery();
});


const value = ref('')
const options = [
  {
    label: '启用',
    value: '1',
  },
  {
    label: '禁用',
    value: '2',
  },
]

const options2 = [
  {
    label: '=',
    value2: '1',
  },
  {
    label: '>',
    value2: '2',
  },
  {
    label: '<',
    value2: '3',
  },
  {
    label: '>=',
    value2: '4',
  },
  {
    label: '<=',
    value2: '5',
  },
]
const value2 = ref(options2.length > 0 ? options2[0].value2 : null);

const value3 = ref('')
const options3 = [
  {
    label: '支付宝',
    value: '1',
  },
  {
    label: '小姜',
    value: '2',
  },
  {
    label: '支付产品',
    value: '3',
  },
]

const value4 = ref('')
const options4 = [
  {
    label: 'aaa',
    value: '1',
  },
  {
    label: '供应商1',
    value: '2',
  },
  {
    label: '供应商2',
    value: '3',
  },
]

/* 静态表格字段 */
const dataList = ref([
  {
    name: '商户1',
    code: 'M100001',
    status: true,
  },
  {
    name: '商户2',
    code: 'M100002',
    status: false,
  },
  {
    name: '商户3',
    code: 'M100001',
    status: true,
  },
  {
    name: '商户4',
    code: 'M100002',
    status: true,
  },
  {
    name: '商户5',
    code: 'M100001',
  },
  {
    name: '商户6',
    code: 'M100002',
    status: true,
  },
  {
    name: '商户7',
    code: 'M100001',
  },
  {
    name: '商户8',
    code: 'M100002',
    status: true,
  },
  {
    name: '商户9',
    code: 'M100001',
    status: true,
  },
  {
    name: '商户10',
    code: 'M100002',
    status: true,
  },
]);
const handleSwitchChange = (row) => {
  const statusText = row.status ? '启用' : '禁用';
  ElMessage.success(`${statusText}成功`);
  // 这里可以添加状态切换的逻辑，例如发起请求等
};

/* 分页 */
const currentPage4 = ref(4)
const pageSize4 = ref(100)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
}
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" style="display: flex;width: 100%;">
        <el-form-item label="" prop="name">
          <el-select v-model="value3" clearable placeholder="上游代付通道" style="width: 150px;">
            <el-option v-for="item in options3" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="" prop="name" style="display: flex;width: 180px;">
          <el-input v-model="queryParams.keywords" placeholder="系统订单号" clearable @keyup.enter="handleQuery" />
        </el-form-item>

        <el-form-item label="" prop="name" style="display: flex;width: 180px;">
          <el-input v-model="queryParams.keywords" placeholder="回调IP" clearable @keyup.enter="handleQuery" />
        </el-form-item>

        <el-form-item label="" prop="name">
          <el-select v-model="value" clearable placeholder="处理状态" style="width: 150px;">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="" prop="name" style="display: flex;width: 180px;">
          <el-input v-model="queryParams.keywords" placeholder="回调参数" clearable @keyup.enter="handleQuery" />
        </el-form-item>

        <el-form-item style="width: 220px;">
          <el-button @click="resetQuery()"><i-ep-refresh />重置</el-button>
          <el-button type="primary" @click="handleQuery()"><i-ep-search />搜索</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container" style="width: 100%;">
      <!-- <template #header>
        <el-button v-hasPerm="['sys:dict_type:add']" type="success" @click="openDialog()"><i-ep-plus />新增</el-button>
        <el-button v-hasPerm="['sys:dict_type:add']" type="success" @click="openDialog()"><i-ep-plus />通道统一配置</el-button>
        <el-button type="danger" :disabled="ids.length === 0" @click="handleDelete()"><i-ep-delete />批量删除</el-button>
      </template> -->
      <el-table
        v-loading="loading"
        highlight-current-row
        :data="dataList"
        border
        class="tabs"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        :row-class-name="tableRowClassName"
      >
        <!-- <el-table-column type="selection" min-width="55" align="center" /> -->
        <el-table-column label="通道名称" prop="name" align="center" min-width="120" fixed />
        <el-table-column label="系统订单号" prop="number" align="center" min-width="200" fixed>
          <template #default="scope">
            <div style="display:flex;">
              <span>{{ scope.row.code }}</span>
              <span v-if="!scope.row.showCheckIcon" @click="toggleIconAndCopy(scope)" style="cursor: pointer;"
                class="copy">
                <el-icon style="color: #1890ff; margin-left: 10px;">
                  <DocumentCopy />
                </el-icon>
              </span>
              <span v-else @click="toggleIconAndCopy(scope)" style="cursor: pointer;" class="copycheck">
                <el-icon style="color: green; margin-left: 10px;">
                  <Check />
                </el-icon>
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="回调IP" prop="remark" align="left" min-width="210">
          <template #default="scope">
            <div style="display:flex;">
              <span>￥100.00 ~ ￥2000.00</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="处理状态" align="center" min-width="100">
          <template #default="{ row }">
            <el-switch v-model="row.status" inline-prompt active-text="启用" inactive-text="禁用"
              @change="handleSwitchChange(row)" />
          </template>
        </el-table-column>

        <el-table-column label="回调地址" prop="remark" align="left" min-width="100">
          <template #default="scope">
            <div style="display:flex;">
              <span>18.00%</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="回调参数" prop="remark" align="left" min-width="170">
          <template #default="scope">
            <div style="display:flex;">
              <span style="">批量分配</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="回调响应" prop="remark" align="left" min-width="170">
          <template #default="scope">
            <div style="display:flex;">
              <span style="">一键权重</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="回调时间" prop="remark" align="left" min-width="170">
          <template #default="scope">
            <div style="display:flex;">
              <span>00:00 ~ 23:59</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="120">
          <template #default="scope">
            <div style="display: flex;">
              <!-- <el-button type="primary" link size="small" @click.stop="openDictDialog(scope.row)">登录</el-button>
              <el-button type="primary" link size="small" @click.stop="openDictDialog(scope.row)">重置密码</el-button> -->
              <el-button v-hasPerm="['sys:dict_type:edit']" type="primary" link size="small"
                @click="messageDialog = true"><span style="font-size: 16px;">详情</span> </el-button>
              <el-button type="primary" link size="small"><span style="font-size: 16px;">重试</span> </el-button>
            </div>
            <!--  <div style="display: flex;">
              <el-button type="primary" link size="small" @click.stop="openDictDialog(scope.row)">对接信息</el-button>
              <el-button v-hasPerm="['sys:dict_type:delete']" type="primary" link size="small"
                @click.stop="handleDelete(scope.row.id)">删除</el-button>
            </div> -->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="handleQuery"
        layout="->,total, sizes, prev, pager, next, jumper" />

      <div class="demo-pagination-block" style="float: right;">
        <div class="demonstration"></div>
        <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4"
          :page-sizes="[100, 200, 300, 400]" :small="small" :disabled="disabled" :background="background"
          layout="total, sizes, prev, pager, next, jumper" :total="400" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 详情 -->
    <el-drawer v-model="messageDialog" title="通道回调信息" :with-header="false" size="50%">
      <p
        style="margin-top: -5px;font-size: 17px;font-weight: 400;display: flex;align-items: center;height: 50px;border-bottom: 1px solid lightgray;">
        <el-icon @click="messageDialog = false" color="gray" style="margin-right: 5px;">
          <Close />
        </el-icon>通道回调信息
      </p>
      <p>系统订单号： <el-icon style="color: #1890ff; margin-left: 10px;" @click="onCopyClick3">
          <DocumentCopy />
        </el-icon></p>
      <div style="display: flex;">
        <span style="width: 400px;">通道名称：衫德-银联打款-02</span>
        <span style="width: 400px;">通道编码：mk-up-2</span>
      </div>
      <p>回调地址：<span
          style="color: #1890ff;border: 1px solid #1890ff;padding: 2px 5px;background-color: aliceblue;">POST</span>
        /api/v1/callback/transfer/mk-up-2/json</p>
      <div style="display: flex;">
        <span style="width: 400px;">请求耗时：0.32秒</span>
        <span style="width: 400px;">处理状态：异常</span>
      </div>
      <p>回调时间：2023/12/22 16:59:33</p>
      <p>回调IP：154.23.187.163（美国科进）</p>
      <p>回调参数： <el-icon style="color: #1890ff; margin-left: 10px;" @click="onCopyClick">
          <DocumentCopy />
        </el-icon></p>

        <div>
        <codemirror
          v-model="jsonString"
          :autofocus="true"
          :indent-with-tab="true"
          :readOnly="true"
        />
      </div>

      <p>请求头： <el-icon style="color: #1890ff; margin-left: 10px;" @click="onCopyClick2">
          <DocumentCopy />
        </el-icon></p>

        <div>
        <codemirror
          v-model="jsonString2"
          :autofocus="true"
          :indent-with-tab="true"
          :readOnly="true"
        />
      </div>
      <p>回调响应：[衫德-银联打款-02]-通道回调; 订单不存</p>
      <p>在; T121302283235Af7kULCv</p>

    </el-drawer>

    <!--字典数据弹窗-->
    <el-dialog v-model="dictDataDialog.visible" :title="dictDataDialog.title" width="1000px" @close="closeDictDialog">
      <dict-item v-model:typeCode="selectedDictType.typeCode" v-model:typeName="selectedDictType.typeName" />
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped>
.example-showcase .el-dropdown+.el-dropdown {
  margin-left: 15px;
}

.app-container {
  height: 100%;

  .table-container {
    height: 100%;
    //background-color: pink;

    .tabs {
      height: calc(100vh - 210px);
      overflow-y: auto;
      //background-color: pink;
    }

  }
}

.demo-pagination-block+.demo-pagination-block {
  // margin-top: 5px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 10px;
}

.code-editor {
  display: flex;
}

.line-numbers {
  counter-reset: line;
  padding: 10px;
  font-family: monospace;
  background-color: #f0f0f0;
  border-right: 1px solid #ccc;
}

.line-number::before {
  content: counter(line);
  counter-increment: line;
  display: block;
  margin-bottom: 1em;
  color: #888;
}

textarea {
  flex: 1;
  padding: 10px;
  font-family: monospace;
  border: none;
  outline: none;
  resize: none; /* 禁用文本框的 resize 功能 */
}

textarea:focus {
  border: none; /* 在选中时隐藏边框 */
  outline: none; /* 在选中时隐藏外轮廓 */
}
::v-deep(.warning-row) {
  opacity: 0.5;
}
</style>
